import {ComponentOptions, PropType} from "vue";
import {BaseCommonMixin} from "./BaseCommonMixin";
import {DefaultProps, DisabledComFunc, EventFirstParam} from "../types";
import {StringUtils} from "../../../utils/StringUtils";
import typeOfUtils from "../../../utils/type-of-utils";


export const ComsCommonMixin: ComponentOptions = {
  mixins: [BaseCommonMixin],
  props: {
    defaultProps: {
      type: Object as PropType<DefaultProps>,
      default: {}
    },
  },
  computed: {
    comValue() {
      return this.defaultProps.row[this.item.prop]
    },
    options() {
      return this.item.props?.options || []
    },
    plusEventsFirstParam(): EventFirstParam {
      return {
        tableData: this.tableData,
        item: this.item,
        row: this.defaultProps.row,
        column: this.defaultProps.column,
        $index: this.defaultProps.$index,
      }
    },
    disabled() {
      if (this.tableVm.$attrs.disabled === true) {
        return true
      }
      // 扩展disabled
      // 判断是否有禁用组件的函数
      let disabledCom = this.tableVm.disabledCom as DisabledComFunc
      if (disabledCom) {
        return disabledCom(this.plusEventsFirstParam)
      }
      let disabled = this.item.props?.disabled
      if (typeOfUtils.isFunction(disabled)) {
        return disabled(this.plusEventsFirstParam)
      }
      return disabled || false
    },
    vBind() {
      // 扩展事件
      let events = {}
      if (this.item.events) {
        Object.keys(this.item.events).forEach(key => {
          let name = 'on' + StringUtils.firstToUp(key)
          events[name] = (...args) => {
            this.item.events[key](this.plusEventsFirstParam, ...args)
          }
        })
      }
      return {
        ...this.item.props,
        disabled: this.disabled,
        ...events,
      }
    }
  },
  created() {
    if (this.tableVm.createdInitValue) {
      this._comInitValue()
    }
  },
  data() {
    return {}
  },
  methods: {
    _comInitValue() {
      if (this.item.initValue) {
        this.defaultProps.row[this.item.prop] = this.item.initValue
      } else {
        if (this.initValue) {
          this.initValue()
        } else {
          this.defaultProps.row[this.item.prop] = ''
        }
      }
    },
    /**
     * 绑定事件的时候，
     * 多个参数用 arguments
     * 单个参数用 $event
     */
    rowUpdateEmitEvent(args, eventName: string) {
      if (this.item && this.item.events && this.item.events[eventName]) {
        if (Array.isArray(args)) {
          this.item.events[eventName](this.plusEventsFirstParam, ...args)
        } else {
          this.item.events[eventName](this.plusEventsFirstParam, args)
        }
      }
      this.tableVm.$emit('rowUpdateEvent',this.plusEventsFirstParam)
    },
    resetField() {
      this._comInitValue()
    },
  }
}
